import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Icon,
  Button,
  Divider,
  Popconfirm,
  BackTop,
  message,
  notification,
} from 'antd';

import StandardTableCustom from '../../customComponents/StandardTableCustom';
import PageHeaderWrapperCustom from '../../customComponents/PageHeaderWrapperCustom';
import CorrelationDrawer from './CorrelationDrawer';

import styles from './List.less';

const FormItem = Form.Item;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ orderProcessing, global, loading }) => ({
  orderProcessing,
  global,
  loading: loading.models.orderProcessing,
}))
@Form.create()
class Standard extends PureComponent {
  isMountedFlag = false;

  state = {
    dataLoading: true,
    processing: false,
    formValues: {},
    // customData: {
    //   count: 0,
    //   list: [],
    //   pagination: {},
    // },
    customData: { list: [] },
    currentKey: null,
    currentRecord: null,
    drawerTitle: '',
    correlationDrawerVisible: false,
    // pageNo: 1,
    // pageSize: 10,
    selectedDataTableDataRows: [],
  };

  componentDidMount() {
    this.isMountedFlag = true;
    const { pageNo, pageSize } = this.state;

    this.loadData({ pageNo, pageSize });
  }

  componentWillUnmount() {
    this.isMountedFlag = false;
  }

  loadData = params => {
    const { dispatch } = this.props;

    const submitData = params;
    submitData.nowpageindex = submitData.pageNo;
    submitData.pagesize = submitData.pageSize;

    this.setState({ dataLoading: true });

    dispatch({
      type: 'orderProcessing/list',
      payload: submitData,
    }).then(() => {
      if (this.isMountedFlag) {
        const {
          orderProcessing: { data },
        } = this.props;

        this.setState({ customData: data, dataLoading: false });
      }
    });
  };

  handleSelectRows = rows => {
    // const list = [];
    // rows.forEach(o => {
    //   list.push(`${o.name}|${o.dataEntityType}`);
    // });
    // const v = list.join();
    // this.setState({
    //   tableList: v,
    // });

    this.setState({
      selectedDataTableDataRows: rows,
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.loadData(params);
  };

  handleFormReset = () => {
    const { form } = this.props;
    const { pageSize } = this.state;

    form.resetFields();
    this.setState({
      formValues: {},
    });

    this.loadData({ pageNo: 1, pageSize });
  };

  refreshGrid = pageNo => {
    const { customData } = this.state;
    const { pagination } = customData;

    const params = {
      pageNo: (pageNo || 1) <= 1 ? 1 : pageNo,
      pageSize: pagination.pageSize,
    };

    this.loadData(params);
  };

  handleSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      this.loadData({
        ...values,
        pageNo: 1,
        pageSize,
      });
    });
  };

  setSingleLineTransit = (e, record) => {
    const { dispatch } = this.props;

    this.setState({ processing: true });

    dispatch({
      type: 'orderProcessing/setSingleLineTransit',
      payload: {
        lineId: record.lineId,
      },
    }).then(() => {
      const {
        orderProcessing: { data },
      } = this.props;

      const { code, message: messageText } = data;
      if (code === 200) {
        setTimeout(() => {
          notification.success({
            placement: 'bottomRight',
            message: '出库操作执行结果',
            description: `’${record.lineName}‘已经设置出库`,
          });
        }, 500);
      } else {
        setTimeout(() => {
          notification.error({
            placement: 'bottomRight',
            message: '操作结果',
            description: messageText,
          });
        }, 500);
      }

      this.setState({ processing: false });
    });
  };

  setSingleLineTransitCannel = (e, record) => {
    message.warn(`线路’${record.lineName}‘取消出库操作`);
  };

  setMultiLineTransit = () => {
    const { dispatch } = this.props;

    this.setState({ processing: true });

    dispatch({
      type: 'orderProcessing/setMultiLineTransit',
      payload: {
        lineIdList: '1,2,3',
      },
    }).then(() => {
      const {
        orderProcessing: { data },
      } = this.props;

      const { code, message: messageText } = data;
      if (code === 200) {
        setTimeout(() => {
          notification.success({
            placement: 'bottomRight',
            message: '出库操作执行结果',
            description: `所选项已经设置出库。`,
          });
        }, 500);
      } else {
        setTimeout(() => {
          notification.error({
            placement: 'bottomRight',
            message: '操作结果',
            description: messageText,
          });
        }, 500);
      }

      this.setState({ processing: false });
    });
  };

  setMultiLineTransitCannel = () => {
    message.warn(`所选线路取消出库操作。`);
  };

  setSingleLinePrint = (e, record) => {
    const { dispatch } = this.props;

    this.setState({ processing: true });

    dispatch({
      type: 'orderProcessing/setSingleLinePrint',
      payload: {
        lineId: record.lineId,
      },
    }).then(() => {
      const {
        orderProcessing: { data },
      } = this.props;

      const { code, message: messageText } = data;
      if (code === 200) {
        setTimeout(() => {
          notification.success({
            placement: 'bottomRight',
            message: '打印操作执行结果',
            description: `’${record.lineName}‘已经传输给打印机。`,
          });
        }, 500);
      } else {
        setTimeout(() => {
          notification.error({
            placement: 'bottomRight',
            message: '操作结果',
            description: messageText,
          });
        }, 500);
      }

      this.setState({ processing: false });
    });
  };

  setSingleLinePrintCannel = (e, record) => {
    message.warn(`线路’${record.lineName}‘取消打印操作。`);
  };

  setMultiLinePrint = () => {
    const { dispatch } = this.props;

    this.setState({ processing: true });

    dispatch({
      type: 'orderProcessing/setMultiLinePrint',
      payload: {
        lineIdList: '1,2,3',
      },
    }).then(() => {
      const {
        orderProcessing: { data },
      } = this.props;

      const { code, message: messageText } = data;
      if (code === 200) {
        setTimeout(() => {
          notification.success({
            placement: 'bottomRight',
            message: '出库操作执行结果',
            description: `所选项已经传输给打印机。`,
          });
        }, 500);
      } else {
        setTimeout(() => {
          notification.error({
            placement: 'bottomRight',
            message: '操作结果',
            description: messageText,
          });
        }, 500);
      }

      this.setState({ processing: false });
    });
  };

  setMultiLinePrintCannel = () => {
    message.warn(`所选线路取消打印操作`);
  };

  showCorrelationDrawer = record => {
    const { lineId } = record;
    const info = `${record.lineName}【共${record.communityCount}个社区】`;

    this.setState({ currentKey: lineId, currentRecord: record, drawerTitle: info }, () => {
      this.setState({ correlationDrawerVisible: true });
    });
  };

  hideCorrelationDrawer = () => {
    this.setState({ correlationDrawerVisible: false });
  };

  onCorrelationDrawerClose = () => {
    this.setState({ correlationDrawerVisible: false });
  };

  renderSimpleForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const { dataLoading, processing } = this.state;

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }} justify="end">
          <Col md={6} sm={24}>
            <FormItem label="线路名称">
              {getFieldDecorator('lineName')(<Input placeholder="请输入线路名称" />)}
            </FormItem>
          </Col>
          <Col md={18} sm={24}>
            <span className={styles.submitButtons}>
              <Button disabled={dataLoading} type="primary" icon="search" htmlType="submit">
                查询
              </Button>
              <Button
                disabled={dataLoading}
                style={{ marginLeft: 8 }}
                icon="reload"
                onClick={this.handleFormReset}
              >
                重置
              </Button>
              <Divider type="vertical" />
              <Popconfirm
                placement="topRight"
                title="所选项开始出库，确定吗？"
                onConfirm={() => this.setMultiLineTransit()}
                onCancel={() => this.setMultiLineTransitCannel()}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  type="primary"
                  icon="export"
                  loading={processing}
                  disabled={dataLoading || processing}
                  // onClick={this.sendOutSelectItem}
                >
                  所选项开始出库
                </Button>
              </Popconfirm>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      customData,
      dataLoading,
      processing,
      currentKey,
      currentRecord,
      drawerTitle,
      correlationDrawerVisible,
      selectedDataTableDataRows,
    } = this.state;

    const columns = [
      {
        title: '线路名称',
        dataIndex: 'lineId',
        align: 'left',
        render: (val, record) => (
          <Fragment>
            <span
              className={styles.pointer}
              onClick={() => {
                this.showCorrelationDrawer(record);
              }}
            >
              {`${record.lineName}【共${record.communityCount}个社区】`}
            </span>
          </Fragment>
        ),
      },
      {
        title: '操作',
        width: 256,
        align: 'right',
        // fixed: 'right',
        render: (text, record) => (
          <Fragment>
            <Popconfirm
              placement="topRight"
              title="将打印三联总单，确定吗？"
              onConfirm={e => this.setSingleLinePrint(e, record)}
              onCancel={e => this.setSingleLinePrintCannel(e, record)}
              okText="确定"
              cancelText="取消"
            >
              <a className={styles.actionButton}>
                <Icon type="printer" className={styles.editButton} />
                打印三联总单
              </a>
            </Popconfirm>
            <Divider type="vertical" />
            <Popconfirm
              placement="topRight"
              title="全部开始出库，确定吗？"
              onConfirm={e => this.setSingleLineTransit(e, record)}
              onCancel={e => this.setSingleLineTransitCannel(e, record)}
              okText="确定"
              cancelText="取消"
            >
              <a className={styles.actionButton}>
                <Icon type="export" className={styles.editButton} />
                开始出库
              </a>
            </Popconfirm>
          </Fragment>
        ),
      },
    ];

    return (
      <PageHeaderWrapperCustom title="待出库订单信息列表">
        <Card className={styles.containorBox} bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTableCustom
              loading={dataLoading || processing}
              data={customData}
              columns={columns}
              pagination={false}
              showSelect
              selectedRows={selectedDataTableDataRows}
              onSelectRow={this.handleSelectRows}
            />
          </div>
        </Card>
        <CorrelationDrawer
          title={drawerTitle}
          recordKey={currentKey}
          record={currentRecord}
          visible={correlationDrawerVisible}
          width={1200}
          onClose={this.hideCorrelationDrawer}
          afterClose={this.onCorrelationDrawerClose}
        />
        <BackTop />
      </PageHeaderWrapperCustom>
    );
  }
}

export default Standard;
